package com.gzone.contentprovider.utils;



import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class HTTPClientUtil {
	private static final String TBD = "http://91.121.156.153/~services/";
	private static final String TAG = "HTTPClientUtil";
	public static String getString(String url) throws Exception {
//		String dataContent = null;
//		try {
//			HttpURLConnection conn = (HttpURLConnection) (new URL(url))
//					.openConnection();
//			conn.setDoInput(true);
//			conn.setDoOutput(true);
//			conn.connect();
//
//			InputStream is = conn.getInputStream();
////			StringBuffer sb = new StringBuffer();
//			int chars;
//			StringBuilder  sb = new StringBuilder();;
//			while ((chars = is.read()) != -1) {
//				sb.append((char) chars);
//			}
//
//			is.close();
//			conn.disconnect();
//			dataContent = sb.toString();
//			return dataContent;
//		} catch (Exception e) {
//			return null;
//		}
		byte[] bs = getBytes(url);
		return new String(bs, "UTF-8");
	}
	public static byte[] getImage(String path){
		Log.i(TAG, "--->" + TBD + path);
		return getBytes(TBD + path);
	}
	public static byte[] getBytes(String url) {
		String dataContent = null;
		try {
			HttpURLConnection conn = (HttpURLConnection) (new URL(url))
			.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.connect();
			
			InputStream is = conn.getInputStream();
			byte[] bytes = toByteArray(is);
			return bytes;
//			StringBuffer sb = new StringBuffer();
//			int chars;
//			while ((chars = is.read()) != -1) {
//				sb.append((char) chars);
//			}
//
//			is.close();
//			conn.disconnect();
//			dataContent = sb.toString();
		} catch (Exception e) {
			return null;
		}
	}
	
	private final static byte[] toByteArray(InputStream fin) {
		byte readBuf[] = new byte[512 * 1024];

		try {
			ByteArrayOutputStream bout = new ByteArrayOutputStream();

			int readCnt = fin.read(readBuf);
			while (0 < readCnt) {
				bout.write(readBuf, 0, readCnt);
				readCnt = fin.read(readBuf);
			}

			fin.close();

			return bout.toByteArray();
		} catch (Exception e) {

			return new byte[0];
		}
	}

	private static final int IO_BUFFER_SIZE = 4 * 1024;


	private static void copy(InputStream in, OutputStream out)
			throws IOException {
		byte[] b = new byte[IO_BUFFER_SIZE];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}

}
